<template>
    <t-card>
            <t-space direction="vertical" style="width: 100%">
                <t-form v-show="showSearch" ref="queryRef" :data="queryParams" layout="inline" reset-type="initial" label-width="calc(4em + 12px)">
                                <t-form-item label="讨论id" name="discussionId">
                                    <t-input v-model="queryParams.discussionId" placeholder="请输入讨论id" clearable @enter="handleQuery" />
                                </t-form-item>
                                <t-form-item label="讨论内容" name="discussionContent">
                                    <t-input v-model="queryParams.discussionContent" placeholder="请输入讨论内容" clearable @enter="handleQuery" />
                                </t-form-item>
                                <t-form-item label="点赞量" name="thumbsUpCount">
                                    <t-input v-model="queryParams.thumbsUpCount" placeholder="请输入点赞量" clearable @enter="handleQuery" />
                                </t-form-item>
                                <t-form-item label="创建时间">
                                    <t-date-range-picker
                                        v-model="dateRangeCreateTime"
                                        style="width: 240px"
                                        allow-input
                                        clearable
                                        separator="-"
                                        :placeholder="['开始日期', '结束日期']"
                                    />
                                </t-form-item>
                    <t-form-item label-width="0px">
                        <t-button theme="primary" @click="handleQuery">
                            <template #icon> <search-icon /></template>
                            搜索
                        </t-button>
                        <t-button theme="default" @click="resetQuery">
                            <template #icon> <refresh-icon /></template>
                            重置
                        </t-button>
                    </t-form-item>
                </t-form>

                <t-table
                    v-model:column-controller-visible="columnControllerVisible"
                    :loading="loading"
                    hover
                    row-key="discussionId"
                    :data="activityDiscussionList"
                    :columns="columns"
                    :selected-row-keys="ids"
                    select-on-row-click
                    :pagination="pagination"
                    :column-controller="{
          hideTriggerButton: true,
        }"
                    :sort="sort"
                    show-sort-column-bg-color
                    @sort-change="handleSortChange"
                    @select-change="handleSelectionChange"
                >
                    <template #topContent>
                        <t-row>
                            <t-col flex="auto">
                                    <t-button v-hasPermi="['xhlj:activityDiscussion:add']" theme="primary" @click="handleAdd">
                                        <template #icon> <add-icon /></template>
                                        新增
                                    </t-button>
                                    <t-button
                                        v-hasPermi="['xhlj:activityDiscussion:edit']"
                                        theme="default"
                                        variant="outline"
                                        :disabled="single"
                                        @click="handleUpdate()"
                                    >
                                        <template #icon> <edit-icon /> </template>
                                        修改
                                    </t-button>
                                    <t-button
                                        v-hasPermi="['xhlj:activityDiscussion:remove']"
                                        theme="danger"
                                        variant="outline"
                                        :disabled="multiple"
                                        @click="handleDelete()"
                                    >
                                        <template #icon> <delete-icon /> </template>
                                        删除
                                    </t-button>
                                    <t-button v-hasPermi="['xhlj:activityDiscussion:export']" theme="default" variant="outline" @click="handleExport">
                                        <template #icon> <download-icon /> </template>
                                        导出
                                    </t-button>
                                        <span class="selected-count">已选 {{ ids.length }} 项</span>
                            </t-col>
                            <t-col flex="none">
                                <t-button theme="default" shape="square" variant="outline" @click="showSearch = !showSearch">
                                    <template #icon> <search-icon /> </template>
                                </t-button>
                                <t-button theme="default" variant="outline" @click="columnControllerVisible = true">
                                    <template #icon> <setting-icon /> </template>
                                    列配置
                                </t-button>
                            </t-col>
                        </t-row>
                    </template>



                            <template #wxUser="{ row }">
            <span v-if="row.wxUser && Object.keys(row.wxUser).length > 1">
              {{ row.wxUser[Object.keys(row.wxUser)[1]] }}（编号为{{ row.wxUser[Object.keys(row.wxUser)[0]] }}）
            </span>
                            </template>

                            <template #activity="{ row }">
            <span v-if="row.activity && Object.keys(row.activity).length > 1">
              {{ row.activity[Object.keys(row.activity)[1]] }}（编号为{{ row.activity[Object.keys(row.activity)[0]] }}）
            </span>
                            </template>




                        <template #operation="{ row }">
                            <t-space :size="8" break-line>
                                    <t-link v-hasPermi="['xhlj:activityDiscussion:query']" theme="primary" hover="color" @click.stop="handleDetail(row)">
                                        <browse-icon />详情
                                    </t-link>
                                    <t-link v-hasPermi="['xhlj:activityDiscussion:edit']" theme="primary" hover="color" @click.stop="handleUpdate(row)">
                                        <edit-icon />修改
                                    </t-link>
                                    <t-link v-hasPermi="['xhlj:activityDiscussion:remove']" theme="danger" hover="color" @click.stop="handleDelete(row)">
                                        <delete-icon />删除
                                    </t-link>
                            </t-space>
                        </template>
                </t-table>
            </t-space>

            <!-- 添加或修改会议交流对话框 -->
            <t-dialog
                v-model:visible="open"
                :header="title"
                destroy-on-close
                :close-on-overlay-click="false"
                width="1100px"
                attach="body"
                :confirm-btn="{
        loading: buttonLoading,
      }"
                @confirm="onConfirm"
            >
                <t-loading :loading="buttonLoading">
                    <t-form
                        ref="activityDiscussionRef"
                        label-align="right"
                        :data="form"
                        :rules="rules"
                        label-width="calc(5em + 41px)"
                        scroll-to-first-error="smooth"
                        @submit="submitForm"
                    >
                                    <t-form-item label="讨论内容" name="discussionContent">
                                        <editor v-model="form.discussionContent" />
                                    </t-form-item>
                                        <t-form-item label="父亲讨论id" name="parentDiscussionId">
                                            <t-input-number v-model="form.parentDiscussionId" placeholder="请输入" />
                                        </t-form-item>
                                        <t-form-item label="活动id编号ID" name="activityId">
                                            <t-input-number v-model="form.activityId" placeholder="请输入" />
                                        </t-form-item>
                                        <t-form-item label="点赞量" name="thumbsUpCount">
                                            <t-input-number v-model="form.thumbsUpCount" placeholder="请输入" />
                                        </t-form-item>
                    </t-form>
                </t-loading>
            </t-dialog>

            <!-- 会议交流详情 -->
            <t-dialog
                v-model:visible="openView"
                header="会议交流详情"
                placement="center"
                width="800px"
                attach="body"
                :footer="false"
            >
                <my-descriptions :loading="openViewLoading">
                                <t-descriptions-item label="讨论id">{{ form.discussionId }}</t-descriptions-item>
                                <t-descriptions-item label="讨论内容" :span="2">
                                    <editor-preview :html-text="form.discussionContent" />
                                </t-descriptions-item>
                                <t-descriptions-item label="父亲讨论id">{{ form.parentDiscussionId }}</t-descriptions-item>
                                <span v-if="form.wxUser && Object.keys(form.wxUser).length > 1">
              {{ form.wxUser[Object.keys(form.wxUser)[1]] }}（编号为{{ form.wxUser[Object.keys(form.wxUser)[0]] }}）
        </span>
                                <span v-if="form.activity && Object.keys(form.activity).length > 1">
              {{ form.activity[Object.keys(form.activity)[1]] }}（编号为{{ form.activity[Object.keys(form.activity)[0]] }}）
        </span>
                                <t-descriptions-item label="点赞量">{{ form.thumbsUpCount }}</t-descriptions-item>
                                <t-descriptions-item label="创建时间">{{ parseTime(form.createTime) }}</t-descriptions-item>
                </my-descriptions>
            </t-dialog>
    </t-card>
</template>
<script lang="ts" setup>
    defineOptions({
        name: 'ActivityDiscussion',
    });
        import {
                AddIcon,
                BrowseIcon,
                DeleteIcon,
                DownloadIcon,
                EditIcon,
            RefreshIcon,
            SearchIcon,
            SettingIcon,
        } from 'tdesign-icons-vue-next';
    import type { FormInstanceFunctions, FormRule, PageInfo, PrimaryTableCol, SubmitContext, TableSort } from 'tdesign-vue-next';
    import { computed, getCurrentInstance, ref } from 'vue';
        import { ArrayOps } from '@/utils/array';

                import type { XhljActivityDiscussionForm, XhljActivityDiscussionQuery, XhljActivityDiscussionVo } from '@/api/xhlj/model/activityDiscussionModel';
                import { listActivityDiscussion, getActivityDiscussion, delActivityDiscussion, addActivityDiscussion, updateActivityDiscussion } from '@/api/xhlj/activityDiscussion';
            import Editor from '@/components/editor/index.vue';
            import EditorPreview from '@/components/editor-preview/index.vue';


    const { proxy } = getCurrentInstance();

        const openView = ref(false);
        const openViewLoading = ref(false);
        const activityDiscussionRef = ref<FormInstanceFunctions>();
        const open = ref(false);
        const buttonLoading = ref(false);
        const title = ref('');
        const activityDiscussionList = ref<XhljActivityDiscussionVo[]>([]);
        const loading = ref(false);
        const columnControllerVisible = ref(false);
        const showSearch = ref(true);
        const total = ref(0);
        const ids = ref([]);
        const single = ref(true);
        const multiple = ref(true);
        const sort = ref<TableSort>();
            const dateRangeCreateTime = ref([]);


        // 校验规则
        const rules = ref<Record<string, Array<FormRule>>>({
        });

        // 列显隐信息
        const columns = ref<Array<PrimaryTableCol>>([
            { title: `选择列`, colKey: 'row-select', type: 'multiple', width: 50, align: 'center' },
                    { title: `讨论内容`, colKey: 'discussionContent', align: 'center', ellipsis: true },
                    { title: `父亲讨论id`, colKey: 'parentDiscussionId', align: 'center' },
                    { title: `创建人wx_user`, colKey: 'wxUser', align: 'center', minWidth: 100, ellipsis: true },
                    { title: `活动id`, colKey: 'activity', align: 'center', minWidth: 100, ellipsis: true },
                    { title: `点赞量`, colKey: 'thumbsUpCount', align: 'center' },
                    { title: `创建时间`, colKey: 'createTime', align: 'center', minWidth: 112, width: 120, sorter: true },
                { title: `操作`, colKey: 'operation', align: 'center', width: 120 },
        ]);
        // 提交表单对象
        const form = ref<XhljActivityDiscussionVo & XhljActivityDiscussionForm>({});
        // 查询对象
        const queryParams = ref<XhljActivityDiscussionQuery>({
            pageNum: 1,
            pageSize: 10,
                        discussionId: undefined,
                        discussionContent: undefined,
                        thumbsUpCount: undefined,
        });
        // 分页
        const pagination = computed(() => {
            return {
                current: queryParams.value.pageNum,
                pageSize: queryParams.value.pageSize,
                total: total.value,
                showJumper: true,
                onChange: (pageInfo: PageInfo) => {
                    queryParams.value.pageNum = pageInfo.current;
                    queryParams.value.pageSize = pageInfo.pageSize;
                    getList();
                },
            };
        });

        /** 查询会议交流列表 */
        function getList() {
            loading.value = true;
                    proxy.addDateRange(queryParams.value, dateRangeCreateTime.value, 'CreateTime');
            listActivityDiscussion(queryParams.value)
                .then((response) => {
                        activityDiscussionList.value = response.rows;
                    total.value = response.total;
                    console.log("ActivityDiscussion", response.rows)
                })
                .finally(() => (loading.value = false));
        }

        // 表单重置
        function reset() {
            form.value = {};
                proxy.resetForm('activityDiscussionRef');
        }

        /** 搜索按钮操作 */
        function handleQuery() {
            queryParams.value.pageNum = 1;
            getList();
        }

        /** 重置按钮操作 */
        function resetQuery() {
                    dateRangeCreateTime.value = [];
            proxy.resetForm('queryRef');
                queryParams.value.pageNum = 1;
                handleSortChange(null);
        }

            /** 排序触发事件 */
            function handleSortChange(value?: TableSort) {
                sort.value = value;
                if (Array.isArray(value)) {
                    queryParams.value.orderByColumn = value.map((item) => item.sortBy).join(',');
                    queryParams.value.isAsc = value.map((item) => (item.descending ? 'descending' : 'ascending')).join(',');
                } else {
                    queryParams.value.orderByColumn = value?.sortBy;
                    queryParams.value.isAsc = value?.descending ? 'descending' : 'ascending';
                }
                getList();
            }

            /** 多选框选中数据 */
            function handleSelectionChange(selection: Array<string | number>) {
                ids.value = selection;
                single.value = selection.length !== 1;
                multiple.value = !selection.length;
            }

        /** 新增按钮操作 */
        function handleAdd() {
            reset();
            open.value = true;
            title.value = '添加会议交流';
        }

        /** 详情按钮操作 */
        function handleDetail(row: XhljActivityDiscussionVo) {
            reset();
            openView.value = true;
            openViewLoading.value = true;
            const discussionId = row.discussionId;
            getActivityDiscussion(discussionId).then((response) => {
                form.value = response.data;
                openViewLoading.value = false;
            });
        }

        /** 修改按钮操作 */
        function handleUpdate(row?: XhljActivityDiscussionVo) {
            buttonLoading.value = true;
            reset();
            open.value = true;
            title.value = '修改会议交流';
            const discussionId = row?.discussionId || ids.value.at(0);
            getActivityDiscussion(discussionId).then((response) => {
                buttonLoading.value = false;
                form.value = response.data;
            });
        }

        /** 提交按钮 */
        function onConfirm() {
                activityDiscussionRef.value.submit();
        }

        /** 提交表单 */
        function submitForm({ validateResult, firstError }: SubmitContext) {
            if (validateResult === true) {
                buttonLoading.value = true;
                const msgLoading = proxy.$modal.msgLoading('提交中...');
                if (form.value.discussionId) {
                        updateActivityDiscussion(form.value)
                            .then(() => {
                                proxy.$modal.msgSuccess('修改成功');
                                open.value = false;
                                    getList();
                            })
                            .finally(() => {
                                buttonLoading.value = false;
                                proxy.$modal.msgClose(msgLoading);
                            });
                } else {
                        addActivityDiscussion(form.value)
                            .then(() => {
                                proxy.$modal.msgSuccess('新增成功');
                                open.value = false;
                                    getList();
                            })
                            .finally(() => {
                                buttonLoading.value = false;
                                proxy.$modal.msgClose(msgLoading);
                            });
                }
            } else {
                proxy.$modal.msgError(firstError);
            }
        }

        /** 删除按钮操作 */
        function handleDelete(row?: XhljActivityDiscussionVo) {
            const discussionIds = row?.discussionId || ids.value;
            proxy.$modal.confirm(`是否确认删除会议交流编号为${discussionIds}的数据项？`, () => {
                const msgLoading = proxy.$modal.msgLoading('正在删除中...');
                return delActivityDiscussion(discussionIds)
                    .then(() => {
                        ids.value = ArrayOps.fastDeleteElement(ids.value, discussionIds);
                        getList();
                        proxy.$modal.msgSuccess('删除成功');
                    })
                    .finally(() => {
                        proxy.$modal.msgClose(msgLoading);
                    });
            });
        }

        /** 导出按钮操作 */
        function handleExport() {
            proxy.addDateRange(queryParams.value, dateRangeCreateTime.value, 'CreateTime');
            proxy.download(
                'xhlj/activityDiscussion/export',
                {
                    ...queryParams.value,
                },
                `activityDiscussion_${new Date().getTime()}.xlsx`,
            );
        }

    getList();
</script>
